package org.gdpu.service.impl;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.gdpu.base.DaoSupport;
import org.gdpu.base.PageView;
import org.gdpu.model.Test;
import org.gdpu.service.TestService;
import org.gdpu.util.ChangeTime;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-6-5
 * Time: 下午9:05
 * To change this template use File | Settings | File Templates.
 */
@Service
@Transactional
public class TestServiceImpl extends DaoSupport<Test> implements TestService {
    private static final Logger logger = LogManager.getLogger(TestServiceImpl.class);

    @Override
    public Test findTestByTheme(String theme) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("theme", theme);
        return (Test) this.findSpecialObject(Test.class, params);
    }

    @Override
    public synchronized String getMaxTestId() {
        Query query = em.createQuery("select max(t.testId) from Test t ");
        String max = (String) query.getResultList().get(0);
        String testId;
        int maxTime;
        int nowTime;
        int maxNum;
        try {
            maxNum = Integer.parseInt(max.substring(6, max.length()));
            maxTime = Integer.parseInt(max.substring(0, 6));
            nowTime = Integer.parseInt(ChangeTime.formatShortYearDate());
        } catch (NumberFormatException e) {
            System.out.println(e);
            return max + 1;
        }
        if (nowTime > maxTime) {
            testId = nowTime + "00000";
        } else {
            maxNum = maxNum + 1;
            String maxNumString = "" + maxNum;
            while (maxNumString.length() < 5) {
                maxNumString = "0" + maxNumString;
            }
            testId = maxTime + maxNumString;
        }
        return testId;


    }

    @Override
    public PageView getTestList(String account, int page, String[] searchName, String[] searchValue) {

        /** 每页显示的结果数 **/
        int maxResult = 10;
        /** 封装的页面数据 **/
        PageView<Test> pageView = new PageView<Test>(maxResult,
                page);
        int firstIndex = ((pageView.getCurrentPage() - 1) * pageView
                .getMaxResult());// 开始索引
        // 按照条件排序
        LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
        orderBy.put("id", "desc");

        /** 列表条件 **/
        StringBuffer jpql = new StringBuffer("1=1");
        /** 列表条件的值 **/
        List<Object> params = new ArrayList<Object>();
        jpql.append(" and (o.owner = ?1 or o.state = 1)");
        params.add(account);
        int flag = 2;
        for (int i = 0; i < searchName.length; i++) {
            try {
                if ("category".equals(searchName[i])) {
                    jpql.append(" and o.category.id = ?").append(flag);
                    int categoryId = Integer.valueOf(searchValue[i]);
                    params.add(categoryId);
                    flag += 1;
                }

                if ("subject".equals(searchName[i])) {
                    if (!"0".equals(searchValue[i])) {
                        jpql.append(" and o.subject.id = ?").append(flag);
                        int subjectId = Integer.valueOf(searchValue[i]);
                        params.add(subjectId);
                        flag += 1;
                    }
                }

            } catch (NumberFormatException e) {
                logger.catching(e);
                return null;
            }

        }

        pageView.setQueryResult(this.getScrollData(Test.class, firstIndex, maxResult, jpql.toString(),
                params.toArray(),orderBy));


        return pageView;
    }


}
